package com.framemodule.base;

import android.content.res.Resources;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.framemodule.BaseApp.BaseApp;
import com.framemodule.R;
import com.framemodule.base.netstatus.NetUtils;
import com.framemodule.utils.Logger;
import com.framemodule.widgets.loading.VaryViewHelperController;
import com.kymjs.frame.view.AppDelegate;
import com.nostra13.universalimageloader.core.ImageLoader;


import cn.bingoogolapple.refreshlayout.BGANormalRefreshViewHolder;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;
import cn.bingoogolapple.refreshlayout.BGARefreshViewHolder;

/**
 * Created by User on 2015/12/14.
 */
public abstract class BaseDelegate extends AppDelegate {

    private BGARefreshLayout mRefreshLayout;
    private PopupWindow toastWindow;
    private Handler handler;

    @Override
    public void initWidget() {
        super.initWidget();
        initTitleBar();
        Logger.e(this.getClass().getSimpleName());
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        try {
                            if (toastWindow != null && toastWindow.isShowing()) {
                                toastWindow.dismiss();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                }
            }
        };
    }

    /**
     * loading view controller
     */
    private VaryViewHelperController mVaryViewHelperController = null;

    /**
     * 初始化标题栏
     */
    public abstract void initTitleBar();

    /**
     * 设置想要多个状态切换的view
     * 加载中。。empty。。error
     *
     * @param id
     */
    public void setVaryView(int id) {
        mVaryViewHelperController = new VaryViewHelperController(get(id));
    }


    /**
     * 初始化下拉刷新布局
     *
     * @param id
     * @param isLoadingMore
     */
    public void initRefreshLayout(int id, boolean isLoadingMore) {
        mRefreshLayout = get(id);
        // 设置下拉刷新和上拉加载更多的风格     参数1：应用程序上下文，参数2：是否具有上拉加载更多功能
        BGARefreshViewHolder refreshViewHolder = new BGANormalRefreshViewHolder(rootView.getContext(), isLoadingMore);
//        BGAStickinessRefreshViewHolder refreshViewHolder = new BGAStickinessRefreshViewHolder(rootView.getContext(), isLoadingMore);
//        refreshViewHolder.setRotateImage(R.mipmap.custom_stickiness_roate);
//        refreshViewHolder.setStickinessColor(R.color.theme_color_text);
        // 设置正在加载更多时的文本
        refreshViewHolder.setLoadingMoreText("加载中...");//加载更多中...
        // 设置下拉刷新和上拉加载更多的风格
        refreshViewHolder.setTopAnimDuration(1000);
        mRefreshLayout.setRefreshViewHolder(refreshViewHolder);
        // 为了增加下拉刷新头部和加载更多的通用性，提供了以下可选配置选项  -------------START
        // 设置正在加载更多时不显示加载更多控件
        mRefreshLayout.setIsShowLoadingMoreView(true);

        // 设置整个加载更多控件的背景颜色资源id
//        refreshViewHolder.setLoadMoreBackgroundColorRes(loadMoreBackgroundColorRes);
        // 设置整个加载更多控件的背景drawable资源id
//        refreshViewHolder.setLoadMoreBackgroundDrawableRes(loadMoreBackgroundDrawableRes);
        // 设置下拉刷新控件的背景颜色资源id
//        refreshViewHolder.setRefreshViewBackgroundColorRes(refreshViewBackgroundColorRes);
        // 设置下拉刷新控件的背景drawable资源id
//        refreshViewHolder.setRefreshViewBackgroundDrawableRes(refreshViewBackgroundDrawableRes);
        // 设置自定义头部视图（也可以不用设置）     参数1：自定义头部视图（例如广告位）， 参数2：上拉加载更多是否可用
//        mRefreshLayout.setCustomHeaderView(mBanner, false);
        // 可选配置  -------------END
    }

    /**
     * 设置刷新布局的代理
     *
     * @param delegate
     */
    public void setRefreshLayoutDelegate(BGARefreshLayout.BGARefreshLayoutDelegate delegate) {
        // 为BGARefreshLayout设置代理
        mRefreshLayout.setDelegate(delegate);
    }

    /**
     * 获取RefreshLayout
     *
     * @return
     */
    public BGARefreshLayout getRefreshLayout() {
        return mRefreshLayout;
    }

    /**
     * 开始刷新
     */
    public void beginRefreshing() {
        mRefreshLayout.beginRefreshing();
    }

    /**
     * 开始加载更多
     */
    public void beginLoadingMore() {
        mRefreshLayout.beginLoadingMore();
    }

    /**
     * 结束刷新
     */
    public void endRefreshing() {
        mRefreshLayout.endRefreshing();
    }

    /**
     * 结束加载更多
     */
    public void endLoadingMore() {
        if (mRefreshLayout != null) {
            mRefreshLayout.endLoadingMore();
        }
    }

    public Resources getResources() {
        return rootView.getResources();
    }

    /**
     * toggle show loading
     *
     * @param toggle
     */
    public void toggleShowLoading(boolean toggle, String msg) {
        if (null == mVaryViewHelperController) {
            throw new IllegalArgumentException("You must return a right target view for loading");
        }

        if (toggle) {
            mVaryViewHelperController.showLoading(msg);
        } else {
            mVaryViewHelperController.restore();
        }
    }


    @Override
    public void toast(CharSequence msg) {
//        CustomToast.makeText(rootView.getContext(), msg, CustomToast.LENGTH_SHORT).show();
//        showToast(msg);
        try {
            if (toastWindow != null && toastWindow.isShowing()) {
                toastWindow.dismiss();
            }
            View toastView = View.inflate(rootView.getContext(), R.layout.toast_layout, null);
            toastWindow = new PopupWindow(toastView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            ((TextView) toastView.findViewById(R.id.message)).setText(msg);
            toastWindow.setOutsideTouchable(false);
            toastWindow.showAtLocation(rootView, Gravity.BOTTOM, 0, BaseApp.screenHeight / 4);
            handler.sendEmptyMessageDelayed(1, 1500);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void toast(CharSequence msg, int gravity) {
//        CustomToast.makeText(rootView.getContext(), msg, CustomToast.LENGTH_SHORT).show();
//        showToast(msg);
        try {
            if (toastWindow != null && toastWindow.isShowing()) {
                toastWindow.dismiss();
            }
            View toastView = View.inflate(rootView.getContext(), R.layout.toast_layout, null);
            toastWindow = new PopupWindow(toastView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            ((TextView) toastView.findViewById(R.id.message)).setText(msg);
            toastWindow.setOutsideTouchable(false);
            toastWindow.showAtLocation(rootView, gravity, 0, 0);
            handler.sendEmptyMessageDelayed(1, 1500);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void toast(CharSequence msg, int gravity, int x, int y) {
//        CustomToast.makeText(rootView.getContext(), msg, CustomToast.LENGTH_SHORT).show();
//        showToast(msg);
        try {
            if (toastWindow != null && toastWindow.isShowing()) {
                toastWindow.dismiss();
            }
            View toastView = View.inflate(rootView.getContext(), R.layout.toast_layout, null);
            toastWindow = new PopupWindow(toastView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            ((TextView) toastView.findViewById(R.id.message)).setText(msg);
            toastWindow.setOutsideTouchable(false);
            toastWindow.showAtLocation(rootView, gravity, x, y);
            handler.sendEmptyMessageDelayed(1, 1500);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void finalize() throws Throwable {
//        handler.removeMessages(1);
        super.finalize();
    }

    /**
     * toggle show empty
     */
    public void toggleShowNewEmpty(boolean toggle) {
        if (null == mVaryViewHelperController) {
            throw new IllegalArgumentException("You must return a right target view for loading");
        }

        if (toggle) {
            mVaryViewHelperController.showNewEmpty();
        } else {
            mVaryViewHelperController.restore();
        }
    }

    /**
     * toggle show network error
     *
     * @param toggle
     * @param onClickListener
     */
    public void toggleShowNewNetworkError(boolean toggle, View.OnClickListener onClickListener) {
        if (null == mVaryViewHelperController) {
            throw new IllegalArgumentException("You must return a right target view for loading");
        }
        if (toggle) {
            if (NetUtils.isNetworkAvailable(rootView.getContext())) {
                mVaryViewHelperController.showNewError(onClickListener);
            } else {
                mVaryViewHelperController.showNewNetworkError(onClickListener);
            }
        } else {
            mVaryViewHelperController.restore();
        }
    }

    /**
     * toggle show error
     *
     * @param toggle
     * @param onClickListener
     */
    public void toggleShowNewError(boolean toggle, View.OnClickListener onClickListener) {
        if (null == mVaryViewHelperController) {
            throw new IllegalArgumentException("You must return a right target view for loading");
        }

        if (toggle) {
            mVaryViewHelperController.showNewError(onClickListener);
        } else {
            mVaryViewHelperController.restore();
        }
    }

    /**
     * 显示AlertDialog
     *
     * @param title    标题
     * @param content  内容
     * @param listener position 为0，取消；为1，确定
     */
    public void showAlert(String title, String content, OnItemClickListener listener) {
        new AlertView(title, content, null, new String[]{"取消", "确定"}, null, rootView.getContext(),
                AlertView.Style.Alert, listener).show();
    }

    /**
     * 显示AlertDialog
     *
     * @param content  内容
     * @param listener position 为0，取消；为1，确定
     */
    public void showAlert1(String content, String cancel, OnItemClickListener listener) {


        AlertView mAlertViewExt = new AlertView(null, null, cancel, null, null, rootView.getContext(), AlertView.Style.Alert, listener);
        ViewGroup extView = (ViewGroup) LayoutInflater.from(rootView.getContext()).inflate(R.layout.alertext_form, null);
        TextView tvContent = extView.findViewById(R.id.tv_dialog_content);
        tvContent.setText(content);
       /* etName = (EditText) extView.findViewById(R.id.etName);
        etName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean focus) {
                //输入框出来则往上移动
                boolean isOpen=imm.isActive();
                mAlertViewExt.setMarginBottom(isOpen&&focus ? 120 :0);
                System.out.println(isOpen);
            }
        });*/
        mAlertViewExt.addExtView(extView);
        mAlertViewExt.show();

    }


}
